package routers

// router 目录负责路由相关内容，如定义路由及路由处理函数，路由加载的中间件等

import (
	"devopsapi/controller/app"
	"devopsapi/controller/index"
	"devopsapi/controller/webhook"
	"devopsapi/docs"
	send "devopsapi/pkg/common"
	"text/template"

	"github.com/gin-gonic/gin"
	swaggerfiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

// Load 中负责加载中间件 middlewares、路由 routes 和 handlers
func Load(r *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {

	// 请求异常处理
	r.NoRoute(send.HandleNotFound)
	r.NoMethod(send.HandleNotFound)

	// 前端项目静态资源
	r.StaticFile("/", "./static/dist/index.html")
	r.StaticFile("/favicon.ico", "./static/dist/favicon.ico")
	r.Static("/assets", "./static/dist/assets")

	// 注册全局模板函数,需要在在加载模板之前
	r.SetFuncMap(template.FuncMap{
		"formatDate": index.FormatAsDate,
		"formatTime": index.FormatAsTime,
	})
	// 加载模板
	r.LoadHTMLGlob("templates/**/*")

	// 单路由
	// r.GET("/app/version", app.Version)

	// Swagger 设置
	docs.SwaggerInfo.BasePath = "/api/v1"

	// 路由组
	_app := r.Group("/app")
	{
		_app.GET("/version", app.Version)
		_app.POST("/restart", app.Restart)
	}

	_v1 := r.Group("/api/v1")
	{
		_v1.POST("/webhook/qywx", webhook.QYWXSendMsg)
		_v1.POST("/webhook/dingtalk", webhook.DingtalkSendMsg)
		_v1.POST("/webhook/email", webhook.EmailSendMsg)
	}

	_html := r.Group("/html")
	{
		_html.GET("/index", index.TemplateHTMLDemo)
	}

	// ginSwagger 路由处理
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))

	// 加载中间件
	r.Use(send.Recover)
	r.Use(mw...)
	return r
}
